package com.bw.controller;

import com.alibaba.fastjson.JSONObject;

import com.bw.entity.User;
import com.bw.mapper.UserMapper;
import org.spring.kun.common.GiteeUtils;
import org.spring.kun.common.JwtUtils;
import org.spring.kun.common.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

@Controller
public class GiteeLoginController {
    @Autowired
    UserMapper userMapper;


    @RequestMapping("/callbackCode.do")
    public String callback(String code, HttpServletResponse response, Model model){
        System.out.println("接收到的临时授权码" + code);

        String token = GiteeUtils.getAccessTokenByCode(code);
        System.out.println("获取到的token " + token);
        JSONObject userInfoByToken = GiteeUtils.getGiteeUserInfoByToken(token);
        System.out.println("获取到的用户信息 " + JSONObject.toJSONString(userInfoByToken));

        // 解析出四个字段  进行注册
        String name = userInfoByToken.getString(GiteeUtils.UserInfoPropertyEnum.LOGIN.getKey());
        String nickName = userInfoByToken.getString("name");
        String avatarUrl = userInfoByToken.getString("avatar_url");
        Integer giteeId = userInfoByToken.getInteger("id");

        // 判断一下之前是否注册过
        User userDB = userMapper.selectByName(name);
        if (userDB == null){
            userDB = new User();
            userDB.setName(name);
            userDB.setNickName(nickName);
            userDB.setAvatarUrl(avatarUrl);
            userDB.setGiteeId(giteeId);
            userMapper.addUser(userDB);
        }else { // 如果之前已经注册过 刷新一下 昵称和头像
            userDB.setNickName(nickName);
            userDB.setAvatarUrl(avatarUrl);
            userMapper.updateById(userDB);
        }

        // 加密用户信息  得到token, 把token放入cookie， 设置cookie过期时间为30min, 把cookie返回给浏览器
        TokenUtils.responseTokenByCookie(userDB,response,30);

        return "redirect:list.do";

    }
}
